﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using System.Text.RegularExpressions;
using work_log.userservices;
using work_log.UserRoleService;
using work_log.RoleService;

namespace work_log {
    public partial class frmReg : DevExpress.XtraEditors.XtraForm {
        /// <summary>
        /// UI线程的同步上下文
        /// </summary>
        SynchronizationContext RegContext = null;
        /// <summary>
        /// service服务
        /// </summary>
        userservices.UserServicesSoapClient userService = null;
        /// <summary>
        /// 是否可以注册
        /// </summary>
        bool flag = false;
        /// <summary>
        /// 空线程
        /// </summary>
        Thread regThread = null;
        /// <summary>
        /// 是否校验通过
        /// </summary>
        bool fCheck1 = false, fCheck2 = false, fCheck3 = false, fCheck4 = false;
        ResultInfoOfUsers resultUser = null;
        ResultInfoOfUsersRoles resultUR = null;
        Users entity = null;
        public frmReg() {
            InitializeComponent();
            RegContext = SynchronizationContext.Current;
            userService = new userservices.UserServicesSoapClient();
        }

        private void frmReg_Load(object sender, EventArgs e) {
            this.txtCode.LostFocus += new EventHandler(uControl_LostFocus);
            this.txtName.LostFocus += new EventHandler(uControl_LostFocus);
            this.txtPwd.LostFocus += new EventHandler(uControl_LostFocus);
            this.txtConPwd.LostFocus += new EventHandler(uControl_LostFocus);
        }

        #region 通用事件
        private void Click_keyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                btnReg_Click(null, null);
            }
        }

        /// <summary>
        /// 校验值为不为空
        /// </summary>
        private bool CheckVal() {
            if (this.txtCode.Text.Trim() == "") {
                lblMSG.Text = "用户名不允许为空！";
                lblMSG.ForeColor = Color.Red;
                this.txtCode.Select();
                return false;
            } else if (this.txtName.Text.Trim() == "") {
                lblMSG.Text = "姓名不允许为空！";
                lblMSG.ForeColor = Color.Red;
                this.txtName.Select();
                return false;
            } else if (this.txtPwd.Text.Trim() == "") {
                lblMSG.Text = "密码不允许为空！";
                lblMSG.ForeColor = Color.Red;
                this.txtPwd.Select();
                return false;
            } else if (this.txtConPwd.Text.Trim() != this.txtPwd.Text.Trim()) {
                lblMSG.Text = "密码不一致！";
                lblMSG.ForeColor = Color.Red;
                this.txtConPwd.Select();
                return false;
            }
            return true;
        }

        private void uControl_LostFocus(object sender, EventArgs e) {
            string reg = "";
            TextBox tb = ((TextBox)sender);
            if (tb.Focused) return;
            switch (tb.Tag.ToString()) {
                case "txtCode":
                    reg = @"^\w+$";
                    if (tb.Text.Trim() == "") {
                        lblMSG.Text = "用户名不能为空！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 14);
                        fCheck1 = false;
                    } else if (!Regex.IsMatch(tb.Text, reg, RegexOptions.Compiled)) {
                        lblMSG.Text = "用户名只能由大小字母、数字以及下划线组成！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 10);
                        fCheck1 = false;
                    } else {
                        entity = new Users();
                        entity.uCode = txtCode.Text.Trim();
                        regThread = new Thread(new ThreadStart(this.CheckCode));
                        regThread.Start();
                        if (flag) {
                            lblMSG.Text = "";
                        }
                    }
                    break;
                case "txtName":
                    reg = @"^[\u4e00-\u9fa5A-Za-z]+$";
                    if (tb.Text.Trim() == "") {
                        lblMSG.Text = "姓名不能为空！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 14);
                        fCheck2 = false;
                    } else if (!Regex.IsMatch(tb.Text, reg, RegexOptions.Compiled)) {
                        lblMSG.Text = "姓名只能是中文或者英文，不能有空格！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 12);
                        fCheck2 = false;
                    } else {
                        lblMSG.Text = "";
                        fCheck2 = true;
                    }
                    break;
                case "txtPwd":
                    reg = @"^[a-zA-z0-9]\w{5,17}$";
                    if (tb.Text.Trim() == "") {
                        lblMSG.Text = "密码不能为空！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 14);
                        fCheck3 = false;
                    } else if (!Regex.IsMatch(tb.Text, reg, RegexOptions.Compiled)) {
                        lblMSG.Text = "密码长度为6~18位，并且只能由大小写字母、数字以及下划线组成！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 9);
                        fCheck3 = false;
                    } else {
                        lblMSG.Text = "";
                        fCheck3 = true;
                    }
                    break;
                case "txtConPwd":
                    if (tb.Text.Trim() == "") {
                        lblMSG.Text = "确认密码不能为空！";
                        lblMSG.Font = new Font("楷体", 14);
                        lblMSG.ForeColor = Color.Red;
                        fCheck4 = false;
                    } else if (tb.Text.Trim() != txtPwd.Text) {
                        lblMSG.Text = "两次密码不一致！";
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 14);
                        fCheck4 = false;
                    } else {
                        lblMSG.Text = "";
                        fCheck4 = true;
                    }
                    break;
            }
        }

        /// <summary>
        /// 检查用户代码是否重复
        /// </summary>
        private void CheckCode() {
            if (entity != null) {
                resultUser = userService.FindByCode(entity);
                if (resultUser.Result && resultUser.MSG != "可以注册") {
                    flag = false;
                    RegContext.Post(RegSafePost, "Check");
                }
            } else {
                XtraMessageBox.Show("无法验证，请联系开发人员！");
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        private void InsertUser() {
            if (entity != null) {
                //用户角色
                UsersRoles ur = new UsersRoles();
                ur.Users_uid = entity.uid;
                ur.Roles_rId = Guid.Parse(new RoleServicesSoapClient().FindByName("user").Table.Rows[0]["rId"].ToString());

                resultUser = new UserServicesSoapClient().Register(entity);
                resultUR = new UsersRolesServicesSoapClient().Add(ur);
                RegContext.Post(RegSafePost, "Insert");
            } else {
                XtraMessageBox.Show("无法注册，请联系开发人员！");
            }
        }

        /// <summary>
        /// 线程操作
        /// </summary>
        /// <param name="text"></param>
        private void RegSafePost(object text) {
            try {
                if (text.ToString() == "Insert") {
                    #region 注册用户
                    if (resultUser != null) {
                        if (resultUser.Result) {
                            if (resultUR != null) {
                                if (resultUR.Result) {
                                    pgWork.Description = "注册成功，正在返回登录页面，请稍后...";
                                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                                    this.Close();
                                } else {
                                    if (entity != null)
                                        new UserServicesSoapClient().Del(entity.uid);
                                    pgWork.Description = "注册失败，请重新尝试...";
                                    pgWork.Visible = false;
                                    this.btnReg.Enabled = true;
                                }
                            }
                        } else {
                            pgWork.Description = "注册失败，请重新尝试...";
                            pgWork.Visible = false;
                            this.btnReg.Enabled = true;
                        }
                    } else {
                        pgWork.Description = "注册失败，请重新尝试...";
                        pgWork.Visible = false;
                        this.btnReg.Enabled = true;
                    }
                    #endregion
                } else if (text.ToString() == "Check") {
                    if (resultUser != null) {
                        lblMSG.Text = resultUser.MSG;
                        lblMSG.ForeColor = Color.Red;
                        lblMSG.Font = new Font("楷体", 12);
                    }
                }
            } catch (Exception ex) {
                if (ex.Message.IndexOf("线程") < 0 && ex.Message.IndexOf("窗口句柄") < 0) {
                    XtraMessageBox.Show("未能连接到服务器，请稍后再试！");
                }

            }
        }
        #endregion

        private void btnReg_Click(object sender, EventArgs e) {
            if (!CheckVal()) return;
            //if (!fCheck1) return;
            if (!fCheck2) return;
            else if (!fCheck3) return;
            else if (!fCheck4) return;
            this.btnReg.Enabled = false;
            pgWork.Description = "正在注册信息，请稍后...";
            pgWork.Visible = true;
            #region 赋值
            entity = new Users();
            entity.uid = Guid.NewGuid();
            entity.uCode = txtCode.Text.Trim();
            entity.uName = txtName.Text.Trim();
            entity.uPassword = txtPwd.Text.Trim();
            entity.uStatus = "1";
            entity.CreateDate = entity.UpdateDate = DateTime.Now;
            #endregion
            lblMSG.Text = "";
            lblMSG.ForeColor = Color.Green;
            regThread = new Thread(new ThreadStart(this.InsertUser));
            regThread.Start();
        }

        private void frmReg_FormClosing(object sender, FormClosingEventArgs e) {
            //if (e.CloseReason == CloseReason.UserClosing) {
            //    if (pgWork.Visible) {
            //        if (XtraMessageBox.Show("正在注册用户信息，是否退出？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) {
            //            if (regThread != null) {
            //                regThread.Abort();
            //            }
            //            this.Close();
            //            return;
            //        }
            //    } else {
            //        if (txtCode.Text.Trim() != "" || txtName.Text.Trim() != "" || txtPwd.Text != "" || txtConPwd.Text != "") {
            //            if (XtraMessageBox.Show("正在填写用户信息，是否退出？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) {
            //                if (regThread != null) {
            //                    regThread.Abort();
            //                }
            //                this.Close();
            //                return;
            //            }
            //        } else {
            //            this.Close();
            //            return;
            //        }
            //    }
            //    e.Cancel = true;
            //}
        }
    }
}